package com.dongdongshop.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.dongdongshop.pojo.cart.Cart;
import com.dongdongshop.pojo.item.TbItem;
import com.dongdongshop.pojo.order_item.TbOrderItem;
import com.dongdongshop.service.cart.CartService;
import com.dongdongshop.service.item.ItemService;
import com.dongdongshop.service.item_jpa.ItemJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.swing.text.html.Option;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Component
@Service
public class CartServiceImpl implements CartService {
    @Reference
    private ItemService itemService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Reference
    private ItemJpaService itemJpaService;
    @Value("${cart.key}")
    private String key;
    /*
    添加购物车逻辑
    * */
    @Override
    public List<Cart> addCartList(List<Cart> cartList, Long itemId, Integer num) {
        //根据ItemId查询Item数据
        /*TbItem item = itemService.getItemById(itemId);*/
        TbItem item = itemJpaService.getItemById(itemId);
        if (item==null){
            throw new RuntimeException("商品不存在");
        }
        if (!"1".equals(item.getStatus())){
            throw new RuntimeException("商品不存在");
        }
        //获取sellerId
        String seller = item.getSeller();
        //根据商家ID判断，原购物车中是否有当前商家的购物车
        Cart cart = getCartBySellerId(cartList,seller);

        if (cart==null){
            Cart newCart = new Cart();
            newCart.setSellerId(seller);
            newCart.setSellerName(item.getSeller());
            List<TbOrderItem> list = new ArrayList<>();
            TbOrderItem tbOrderItem = getTbOrderItem(num, item);
            list.add(tbOrderItem);
            newCart.setOrderItemList(list);
            cartList.add(newCart);
        }else {//如果购物车列表中存在该商家的购物车
            TbOrderItem orderItem = getTbOrderItemByItemId(cart.getOrderItemList(), itemId);
            if (orderItem==null){
                orderItem = getTbOrderItem(num, item);
                cart.getOrderItemList().add(orderItem);
            }else {
                orderItem.setNum(orderItem.getNum()+num);
                //总数量成于单价
                orderItem.setTotalFee(new BigDecimal(orderItem.getNum()*item.getPrice().doubleValue()));
                if (orderItem.getNum()<=0){
                    cart.getOrderItemList().remove(orderItem);
                }
                if (cart.getOrderItemList().isEmpty()){
                    cartList.remove(cart);
                }
            }
        }

        return cartList;
    }

    @Override
    public List<Cart> getCarListFromRedis(String username) {
        List<Cart> cartList = (List<Cart>) redisTemplate.opsForHash().get(key,username);
        Optional<List<Cart>> optional = Optional.ofNullable(cartList);
        return optional.orElse(new ArrayList<>());
    }

    @Override
    public void savaCartListToRedis(String username, List<Cart> cartList) {
        redisTemplate.opsForHash().put(key,username,cartList);
    }

    @Override
    public List<Cart> mergeCartListCookieAndRedis(List<Cart> cartList, List<Cart> cartListFromRedis) {
        for (Cart cart : cartList) {
            for (TbOrderItem tbOrderItem : cart.getOrderItemList()) {
                cartListFromRedis = addCartList(cartListFromRedis,tbOrderItem.getItemId(),tbOrderItem.getNum());
            }
        }
        return cartListFromRedis;
    }

    //根据商家id查询购物车实体
    private Cart getCartBySellerId(List<Cart> cartList,String sellerId){
        for (Cart cart : cartList) {
            if (Objects.equals(cart.getSellerId(),sellerId)){
                return cart;
            }
        }
        return null;
    }
    //根据itemid查询购物车明细表中是否存在该购物车明细
    private TbOrderItem getTbOrderItemByItemId(List<TbOrderItem> orderItemList,Long itemId){
        for (TbOrderItem tbOrderItem : orderItemList) {
            if (Objects.equals(tbOrderItem.getItemId(),itemId)){
                return tbOrderItem;
            }
        }
        return null;
    }
    private TbOrderItem getTbOrderItem(Integer num,TbItem item){
        TbOrderItem tbOrderItem = new TbOrderItem();
        tbOrderItem.setNum(num);
        tbOrderItem.setTitle(item.getTitle());
        tbOrderItem.setTotalFee(new BigDecimal(num*item.getPrice().doubleValue()));
        tbOrderItem.setPrice(item.getPrice());
        tbOrderItem.setPicPath(item.getImage());
        tbOrderItem.setItemId(item.getId());
        tbOrderItem.setGoodsId(item.getGoodsId());
        tbOrderItem.setSellerId(item.getSellerId());
        return tbOrderItem;
    }
}
